// 主应用程序控制器
class GamePlatform {
    constructor() {
        this.currentScreen = 'login-screen';
        this.initializeApp();
    }

    // 初始化应用
    initializeApp() {
        // 检查是否已登录
        if (authManager.isLoggedIn()) {
            this.showGameMenu();
        } else {
            this.showLoginScreen();
        }

        this.bindEvents();
    }

    // 显示登录界面
    showLoginScreen() {
        this.switchScreen('login-screen');
    }

    // 显示游戏菜单
    showGameMenu() {
        document.getElementById('current-user').textContent = authManager.getCurrentUser();
        this.switchScreen('game-menu');
    }

    // 显示游戏界面
    showGame(gameName) {
        switch (gameName) {
            case 'tetris':
                this.switchScreen('tetris-game');
                if (!tetrisGame) {
                    tetrisGame = new TetrisGame();
                }
                break;
        }
    }

    // 切换界面
    switchScreen(screenId) {
        // 隐藏所有界面
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.remove('active');
        });

        // 显示目标界面
        document.getElementById(screenId).classList.add('active');
        this.currentScreen = screenId;
    }

    // 绑定事件
    bindEvents() {
        // 登录表单提交
        document.getElementById('login-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            if (authManager.login(username, password)) {
                this.showGameMenu();
            } else {
                alert('请输入用户名和密码');
            }
        });

        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', () => {
            authManager.logout();
            this.showLoginScreen();
            // 清空登录表单
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
        });

        // 游戏卡片点击
        document.querySelectorAll('.game-card').forEach(card => {
            card.addEventListener('click', () => {
                const gameName = card.dataset.game;
                this.showGame(gameName);
            });
        });

        // 返回菜单按钮
        document.getElementById('back-to-menu').addEventListener('click', () => {
            this.showGameMenu();
        });

        // 俄罗斯方块游戏控制
        document.getElementById('start-game').addEventListener('click', () => {
            if (tetrisGame) {
                tetrisGame.startGame();
            }
        });

        document.getElementById('pause-game').addEventListener('click', () => {
            if (tetrisGame) {
                tetrisGame.togglePause();
            }
        });
    }
}

// 当页面加载完成后启动应用
document.addEventListener('DOMContentLoaded', () => {
    new GamePlatform();
});